package com.lightsh.flashlight;

import com.lightsh.light.Light;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.util.Log;
import android.widget.Toast;

public class Switcher extends BroadcastReceiver{

	public static final String EXTRA_BRIGHTNESS = "Extra_Brightness";
	public static final String BROADCAST_NAME = "com.lightsh.flashlight.switcher.msg";
	@Override
	public void onReceive(Context context, Intent intent) {
		if(!Light.isAvailable()){
			Toast.makeText(context, R.string.needMx, Toast.LENGTH_SHORT).show();
			return;
		}
		if(intent.getExtras() != null && intent.getExtras().containsKey(EXTRA_BRIGHTNESS)){
			Intent activityIntent = new Intent(context, BrightnessSetActivity.class);
			activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(activityIntent);
			return;
		}
		
		if(Light.isOpen()){
			tryClose(context);
		}else{
			tryOpen(context);
		}
		LightSwitchWidget.updateAllViews(context);
	}

	private static final String POWER_LOCK_KEY = "COM_LIGHTSH_FLASHLIGHT_POWER_LOCK";
	private static final long POWER_LOCK_TIMEOUT = 10 * 60 * 1000;
	private static WakeLock sWakeLock = null;
	private static void lockPower(Context context, boolean bLock) {
		if (sWakeLock == null) {
			PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
			sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, POWER_LOCK_KEY);
			sWakeLock.setReferenceCounted(false);
//			Log.w("", "init wake lock");
		}
		if (bLock) {
			if (sWakeLock != null && !sWakeLock.isHeld()) {
				sWakeLock.acquire(POWER_LOCK_TIMEOUT);
//				Log.w("", "lock light");
			}
		} else {
			if (sWakeLock != null && sWakeLock.isHeld()) {
				sWakeLock.release();
//				Log.w("", "release light");
			}
		}
	}
	public static final void tryOpen(Context context){
		Light.set(LightSwitchWidget.getCur(context));
		Light.open();
		lockPower(context, true);
	}
	public static final void tryClose(Context context){
		Light.close();
		lockPower(context, false);
	}
}
